package com.power.web;

import com.github.pagehelper.PageInfo;
import com.power.model.TUser;
import com.power.query.UserQuery;
import com.power.result.R;
import com.power.service.UserService;
import com.power.util.LoginInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 获取登录信息
     *
     * @return
     */
    @GetMapping(value = "/api/login/info")
    public R getLoginInfo() {
        return R.OK(LoginInfoUtil.getCurrentLoginUser());
    }

    /**
     * 免登录接口
     *
     * @return
     */
    @GetMapping(value = "/api/login/free")
    public R freeLogin() {
        return R.OK();
    }

    /**
     * 用户列表
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/api/users")
    public R userPage(@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                      @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        PageInfo<TUser> userByPage = userService.getUserByPage(currentPage, pageSize);
        return R.OK(userByPage);
    }

    @GetMapping(value = "/api/user/{id}")
    public R userDetail(@PathVariable("id") Integer id) {
        TUser tUser = userService.selectUserById(id);
        return R.OK(tUser);
    }

    @PostMapping(value = "/api/user")
    public R addUser(UserQuery userQuery, @RequestHeader(value = "token") String token) {
        userQuery.setToken(token);
        int saveCount = userService.saveUser(userQuery);
        return saveCount >= 1 ? R.OK() : R.FAIL();
    }

    @PutMapping(value = "/api/user")
    public R editUser(UserQuery userQuery, @RequestHeader(value = "token") String token) {
        userQuery.setToken(token);
        int editCount = userService.editUser(userQuery);
        return editCount >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value = "/api/user/{id}")
    public R deleteUser(@PathVariable("id") Integer id) {
        int deleteCount = userService.deleteUser(id);
        return deleteCount >= 1 ? R.OK() : R.FAIL();
    }

    @DeleteMapping(value = "/api/user")
    public R batchDelUser(@RequestParam(value = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        int delCount = userService.batchDelUserIds(idList);
        return delCount >= idList.size() ? R.OK() : R.FAIL();
    }

    @GetMapping(value = "/api/ownerList")
    public R ownerList() {
        List<TUser> userList = userService.getOwnerList();
        return R.OK(userList);
    }
}
